const Router = require('@koa/router');
const router = new Router()
const multer = require('@koa/multer')
const path = require('path'); 
const fs = require('fs'); 

router.post('/upload', async (ctx) => {
  const { file } = ctx.request.files;
  if (file) {
    ctx.body = { url: file.newFilename, name: file.originalFilename }
  } else {
      ctx.body = '上传出错'
  }
})

const uploadDir = path.join(__dirname, '../uploads');  

router.post('/download/:filename', async (ctx) => {
  const fileName = ctx.params.filename
  const filePath = path.join(uploadDir, fileName); // 构建文件完整路径  
  // 检查文件是否存在  
  if (fs.existsSync(filePath)) {  
    // 设置响应头，告诉浏览器这是一个需要下载的文件  
    ctx.set('Content-Disposition', `attachment; filename=${fileName}`);  
    ctx.set('Content-Type', 'application/pdf'); // 设置正确的 MIME 类型  

    // 读取文件内容并发送给客户端  
    const fileStream = fs.createReadStream(filePath);  
    ctx.body = fileStream;  
  } else {  
    // 文件不存在，返回错误响应  
    ctx.status = 404;  
    ctx.body = 'File not found';  
  }  
})

module.exports = router